const express = require("express");
const router = express.Router();
const https = require("https"); //引入https模块
const util = require("util"); //引入util工具包格式化路径
const fs = require("fs");
const crypto = require("crypto");
const accessTokenJson = require("./access_token.json");
const configJson = require("./config.json");


// 获取access_token
router.get('/accessToken', function (req, res, next) {
    new Promise(function (resolve, reject) {
        //获取当前时间 
        let currentTime = new Date().getTime();
        //格式化请求地址
        let url = util.format(configJson.apiURL.accessTokenApi, configJson.apiDomain, configJson.appID, configJson.appScrect);
        //判断 本地存储的 access_token 是否有效
        if (accessTokenJson.access_token === "" || accessTokenJson.expires_time < currentTime) {

            https.get(url, function (res) {
                let buffer = [],
                    result = "";
                // 监听 data 事件
                res.on("data", function (data) {
                    buffer.push(data);
                });
                res.on("end", function () {
                    let body = Buffer.concat(buffer);
                    result = JSON.parse(body);
                    if (body.indexOf("errcode") < 0) {
                        accessTokenJson.access_token = result.access_token;
                        accessTokenJson.expires_time = new Date().getTime() + (parseInt(result.expires_in) - 200) * 1000;
                        //更新本地存储的
                        fs.writeFile("./access_token.json", JSON.stringify(accessTokenJson), function (err) {});
                        //将获取后的 access_token 返回
                        resolve(accessTokenJson.access_token);
                    } else {
                        resolve(result);
                    }
                });
            }).on('error', function (err) {
                reject(err);
            });
        } else {
            //将本地存储的 access_token 返回
            resolve(accessTokenJson.access_token);
        }
    }).then(function (data) {
        res.send(data);
    });
});

// 获取jsapi_ticket
const jsapiTicket = require("./jsapi_ticket.json");
router.get("/jsapiTicket", function (req, res, next) {
    new Promise(function (resolve, reject) {
        let currentTime = new Date().getTime();
        if (accessTokenJson.access_token != "" && (jsapiTicket.ticket === "" || jsapiTicket.expires_time < currentTime)) {
            https.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessTokenJson.access_token}&type=jsapi`, function (res) {
                let buffer = [],
                    result = "";
                res.on("data", function (data) {
                    buffer.push(data);
                });
                res.on("end", function () {
                    let body = Buffer.concat(buffer);
                    result = JSON.parse(body);
                    if (result.errcode === 0) {
                        jsapiTicket.ticket = result.ticket;
                        jsapiTicket.expires_time = new Date().getTime() + (parseInt(result.expires_in) - 200) * 1000;
                        fs.writeFile("./jsapi_ticket.json", JSON.stringify(jsapiTicket), function (err) {
                            console.log(err);
                        });
                        resolve(jsapiTicket.ticket);
                    } else {
                        resolve(result);
                    }
                })
            }).on("error", (err) => {
                reject(err);
            })
        } else {
            resolve(jsapiTicket.ticket);
        }
    }).then((data) => {
        res.send(data)
    });
});

// 生成signature签名
const signaTure = require("./signature.json");
// 获取随机长度随机字符串
function randomString(length) {
    let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';
    for (let i = length; i > 0; --i)
        result += str[Math.floor(Math.random() * str.length)];
    return result;
};
router.get("/signature", function (req, res, next) {
    // 本地写入数据
    function getSign() {
        signaTure.noncestr = randomString(12);
        signaTure.jsapi_ticket = jsapiTicket.ticket;
        signaTure.timestamp = Math.ceil((new Date().getTime()) / 1000);
        signaTure.url = req.query.url;
        fs.writeFile("./signature.json", JSON.stringify(signaTure), function (err) {
            console.log(err);
        });
    };
    getSign();
    // 按照Ascll码的大小进行排序
    function sort_ASCII(obj) {
        let arr = new Array();
        let num = 0;
        for (let i in obj) {
            arr[num] = i;
            num++;
        }
        let sortArr = arr.sort();
        let sortObj = {};
        for (let i in sortArr) {
            sortObj[sortArr[i]] = obj[sortArr[i]];
        }
        return sortObj;
    };
    const keys = Object.keys(sort_ASCII(signaTure));
    let newArr = "";
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const value = sort_ASCII(signaTure)[key];
        newArr += `${key}=${value}&`;
    };
    newArr = crypto.createHash("sha1").update(newArr.slice(0, -1)).digest("hex");
    res.send({...signaTure,signature:newArr});
});


module.exports = router;